package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC916 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public List<String> wordSubsets(String[] words1, String[] words2) {
            List<String> res = new ArrayList<>();
            final int[] maxCnt = getOrder(words2);
            for (String word : words1) {
                int[] cnt = new int[26];
                for (char c : word.toCharArray()) {
                    cnt[c - 'a']++;
                }

                boolean curAdd = true;
                for (int i = 0; i < 26; i++) {
                    if (maxCnt[i] > cnt[i]) {
                        curAdd = false;
                        break;
                    }
                }

                if (curAdd) res.add(word);
            }

            return res;
        }

        public int[] getOrder(String[] words2) {
            int[] maxCnt = new int[26];

            for (String word : words2) {
                int[] cnt = new int[26];
                for (char c : word.toCharArray()) {
                    cnt[c - 'a']++;
                }

                for (int i = 0; i < 26; i++) {
                    maxCnt[i] = Math.max(maxCnt[i], cnt[i]);
                }
            }

            return maxCnt;
        }
    }

    public void run() {
        Solution solution = new Solution();

//        示例 1：
//        输入：words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]
//        输出：["facebook","google","leetcode"]
//        String[] words1 = {"amazon", "apple", "facebook", "google", "leetcode"}, words2 = {"e", "o"};
//        System.out.println(solution.wordSubsets(words1, words2));

//        示例 5：
//        输入：words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["ec","oc","ceo"]
//        输出：["facebook","leetcode"]
        String[] words1 = {"amazon", "apple", "facebook", "google", "leetcode"}, words2 = {"ec", "oc", "ceo"};
        System.out.println(solution.wordSubsets(words1, words2));
    }

    public static void main(String[] args) throws Exception {
        LC916 an = new LC916();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
